package handler

import (
	"git.oschina.net/fanbuchi/redpack/constant"
	"git.oschina.net/fanbuchi/redpack/domain"
	"git.oschina.net/fanbuchi/redpack/errors"
	"git.oschina.net/fanbuchi/redpack/service"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"net/http"
)

type OauthHandler struct {
	*service.OauthService
}


// @Summary 授权
// @Description 登陆授权token
// @Tags oauth
// @Accept  json
// @Produce  json
// @Param   account     body    domain.LoginReq     true        "账户和密码"
// @Param   Authorization     header    string     true        "权限认证" default(Basic Y2xpZW50OnNlY3JldA==)
// @Success 200 {object} domain.Oauth    "调用成功"
// @Failure 400 {object} domain.Rsp "失败，参数错误!"
// @Router /oauth/token [post]
func  (handler*OauthHandler)Token(c *gin.Context)  {
	var params domain.Account
	// ShouldBindQuery GET
	// ShouldBind get/post
	//ShouldBindBodyWith
	if err := c.ShouldBindJSON(&params); err != nil {
		c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusBadRequest,Msg:err.Error()})
		return
	}
	result,err:=handler.OauthService.Token(&params)

	if err!=nil {
		if err==gorm.ErrRecordNotFound {
			c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusForbidden,Msg:_error.ErrAccountPassword.Error()})
			return
		}
		c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusForbidden,Msg:err.Error()})
		return
	}
	c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusOK,Data:result})
}



// @Summary 退出登陆
// @Description 清除授权token
// @Tags oauth
// @Accept  json
// @Produce  json
// @Param   Authorization     header    string     true        "权限认证" default(Bearer 3bbea1b6-f8e4-4da9-a9f3-0413abff47c5)
// @Success 200 {object} domain.Rsp    "退出成功"
// @Router /oauth/logout [get]
func  (handler*OauthHandler)Logout(c *gin.Context)  {
	accountId := c.MustGet(constant.AccountId)
	id:=accountId.(int64)

	oauth:=domain.Oauth{}
	oauth.AccountId=id
	 _,err:=handler.OauthService.Logout(&oauth)
	if err!=nil {
		c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusForbidden,Msg:err.Error()})
		return
	}
	c.JSON(http.StatusOK, domain.Rsp{Status:http.StatusOK,Msg:"退出成功"})
}

